<!--
禁止修改!此文件是产品代码的一部分，后续可能变更或者不再开放。
若有问题，请参考前端相关二开文档。
-->
<template>
  <h3-popup-modal
    :visible="popVisible"
    maskClosable
    :round="!!$route.query.workflowInstanceId"
    :wrapCls="
      'workflow-track-wrapper' +
      (!$route.query.workflowInstanceId ? ' single-route' : '')
    "
    @hide="$emit('cancel')"
  >
    <template #header>
      <h3-tabs v-model="index" :tabsList="tabsList" />
      <span
        v-if="$route.query.workflowInstanceId"
        class="icon aufontAll h-icon-all-close"
        @click="$emit('cancel')"
      ></span>
    </template>
    <div class="workflow-track" :class="{ external: isExternal }">
      <div class="tab-content" :class="{ 'show-devops': devOpsVisible }">
        <div class="scroll">
          <Approvals
            v-show="popVisible && index === 'approval'"
            :workflowBaseInfo="workflowBaseInfo || workflowInfo"
            :workflowInstanceId="workflowInstanceId"
          />
          <!-- 流程图 -->
          <Chart
            v-show="popVisible && index === 'chart'"
            :show="popVisible && index === 'chart'"
            :workflowStatus="workflowInfo.status"
          />
        </div>
      </div>
      <div v-if="devOpsVisible" class="devOps form-actions">
        <h3-button @click="toDevOps">流程运维</h3-button>
      </div>
    </div>
  </h3-popup-modal>
</template>

<script lang="ts">
import { workflow, workflowApi } from 'cloudpivot/api';
import flow from 'cloudpivot-flow/flow/mobile';
import { renderer } from 'cloudpivot-form/form';
import * as mobileForm from 'cloudpivot-form/form/mobile';
import { H3Tabs } from 'cloudpivot-mobile-vue';
import { Component, Vue, Prop, Watch } from 'vue-property-decorator';
import { H3Button, H3Switch, H3PopupModal } from '@h3/thinking-ui';
import { getUrlStroage } from 'cloudpivot/common/src/utils/url';

@Component({
  name: 'workflow-track',
  components: {
    H3Tabs,
    Approvals: flow.components.Approval,
    Chart: flow.components.WorkflowChart,
    FormActions: mobileForm.runtime.FormActions,
    H3PopupModal,
    H3Button,
  },
})
export default class WorkflowTrack extends Vue {
  @Prop({ default: true })
  popVisible!: boolean;

  @Prop({ default: null })
  workflowBaseInfo!: any;

  index = '';

  workflowInfo: any = {};

  @Watch('popVisible')
  onVisibleChange() {
    if (this.popVisible && !this.index) {
      if ((window as any).isExternal) {
        this.index = 'chart';
      } else {
        this.index = 'approval';
      }

      if (!this.$route.query.workflowInstanceId) {
        this.loadAsync();
      }
    }
  }

  //表单内打开是query上，单独页面打开是params上
  get workItemId() {
    return (this.$route.query.workitemId ||
      this.$route.params.workitemId) as any;
  }

  //表单内打开是query上，单独页面打开是params上
  get workflowInstanceId() {
    return (
      this.popVisible &&
      ((this.$route.query.workflowInstanceId ||
        this.$route.params.workflowInstanceId) as any)
    );
  }

  get tabsList() {
    if (this.isExternal) {
      return [
        {
          code: 'chart',
          name: this.$t('languages.common.workflowChart'),
        },
      ];
    }
    return [
      {
        code: 'approval',
        name: this.$t('languages.common.approval'),
      },
      {
        code: 'chart',
        name: this.$t('languages.common.workflowChart'),
      },
    ];
  }

  @Watch('workflowBaseInfo', { immediate: true })
  onWorkflowBaseInfoChange() {
    if (this.workflowBaseInfo) {
      this.workflowInfo = this.workflowBaseInfo;
    }
  }

  @Watch('workflowInfo')
  onWorkflowInfoChange() {
    //获取菜单权限
    if (
      this.workflowInfo &&
      this.workflowInfo.headerAction &&
      typeof this.workflowInfo.headerAction === 'object'
    ) {
      const dataMap = new Map()
        .set('showEditable', 'languages.common.edit')
        .set('showAdjust', 'languages.common.adjust')
        .set('showRemove', 'languages.common.delete')
        .set('showCancel', 'languages.common.void')
        .set('showEditOwner', 'languages.common.updateOwner');
      this.mobileActions.forEach((item) => {
        this.$set(item, 'visible', this.workflowInfo.headerAction[item.code]);
        item.text = this.$t(`${dataMap.get(item.code)}`);
      });
      this.mobileActions = this.mobileActions.filter((item) => item.visible);
    }
  }

  toDevOps() {
    const urls = window.location.href.split('#')[0];
    if (urls.indexOf('?')) {
      const url = `/mobile/#/form/devOps/${this.workflowInstanceId}`;
      window.location.href = url;
    } else {
      this.$router
        .push({
          name: 'devOps',
          params: {
            workflowInstanceId: this.workflowInstanceId,
            workflowVersion: this.workflowInfo.workflowVersion,
            workflowCode: this.workflowInfo.workflowCode,
            workflowName: this.workflowInfo.workflowName,
            participants: this.workflowInfo.participants,
            headerAction: this.workflowInfo.headerAction,
            status: this.workflowInfo.status,
          },
          query: {
            return: this.$route.query.return,
            workItemId: this.workItemId,
          },
        })
        .catch((err: any) => {
          console.log(err);
        });
    }
  }

  get devOpsVisible() {
    return this.mobileActions.some((el) => el.visible);
  }

  mobileActions: any[] = [
    {
      code: 'showEditable',
      disabled: false,
      visible: true,
      loading: false,
      text: '编辑',
    },
    {
      code: 'showAdjust',
      disabled: false,
      visible: true,
      loading: false,
      text: '调整节点',
    },
    {
      code: 'showRemove',
      disabled: false,
      visible: true,
      loading: false,
      text: '删除',
    },
    {
      code: 'showCancel',
      disabled: false,
      visible: true,
      loading: false,
      text: '作废',
    },
    {
      code: 'showEditOwner',
      disabled: false,
      visible: true,
      loading: false,
      text: '修改拥有者',
    },
  ];

  // 是否为外部用户
  get isExternal() {
    if ((window as any).isExternal) {
      return true;
    }
    return false;
  }

  /**
   * 流程处理
   */
  onAction(ac: any) {
    switch (ac.code) {
      case 'showRemove': //删除
        this.deleteForm();
        break;
      case 'showCancel': //作废
        this.nullify();
        break;
      case 'showEditOwner': //修改拥有者
        this.editOwner();
        break;
      case 'showEditable': //编辑
        this.edit();
        break;
      case 'showAdjust': //调整节点
        this.adjustNode();
        break;
      default:
        break;
    }
  }

  /**
   * 编辑
   */
  edit() {
    this.$router
      .push({
        name: 'form-detail',
        query: {
          workitemId: this.workItemId,
          workflowInstanceId: this.workflowInstanceId,
          edit: 'true',
          return: '/',
        },
      })
      .catch((err: any) => {
        console.log(err);
      });
  }

  /**
   * 调整节点
   */

  adjustNode() {
    this.$router
      .push({
        name: 'WorkflowAdjustment',
        params: {
          workflowInstanceId: this.workflowInstanceId,
        },
        query: {
          return: this.$route.query.return,
          workItemId: this.workItemId,
        },
      })
      .catch((err: any) => {
        console.log(err);
      });
  }

  /**
   * 修改拥有者
   */
  editOwner() {
    this.$router
      .push({
        name: 'WorkflowUpdateTenedor',
        params: {
          workflowInstanceId: this.workflowInstanceId,
          workItemId: this.workItemId,
        },
        query: {
          return: this.$route.query.return,
        },
      })
      .catch((err: any) => {
        console.log(err);
      });
  }

  /**
   * 作废
   */
  async nullify() {
    this.$h3.modal.show({
      title: `${this.$t('cloudpivot.flow.pc.NullifyTips1')}`,
      content: `${this.$t('cloudpivot.flow.pc.NullifyTips2')}`,
      actions: [
        {
          //@ts-ignore
          text: this.$t('cloudpivot.form.renderer.cancel').toString(),
          onPress() {},
        },
        {
          //@ts-ignore
          text: this.$t('cloudpivot.form.renderer.ok').toString(),
          onPress: async () => {
            const res = await workflowApi.abortInstance(
              this.workflowInstanceId,
              this.workItemId,
              1,
            );
            if (res.errcode === 0) {
              const url: any =
                getUrlStroage(this.$route.query.return) ||
                this.$route.query.return;
              this.$router.push({ path: url + '?' + new Date().getTime() });
            } else {
              this.$h3.toast.show({
                text: res.errmsg as string,
                iconType: 'close',
              });
            }
          },
        },
      ],
    });
  }

  /**
   * 删除
   */
  async deleteForm() {
    this.$h3.modal.show({
      title: `${this.$t('cloudpivot.flow.pc.DeleteTips3')}`,
      content: `${this.$t(
        'cloudpivot.flow.pc.DeleteTips1',
      )}<span style="color:#F4454E">${this.$t(
        'cloudpivot.flow.pc.DeleteTips2',
      )}</span>`,
      actions: [
        {
          //@ts-ignore
          text: this.$t('cloudpivot.form.renderer.cancel').toString(),
          onPress() {},
        },
        {
          //@ts-ignore
          text: this.$t('cloudpivot.form.renderer.ok').toString(),
          onPress: async () => {
            const res = await workflowApi.deleteInstance(
              this.workflowInstanceId,
              this.workItemId,
              1,
            );
            if (res.errcode === 0) {
              const url: any =
                getUrlStroage(this.$route.query.return) ||
                this.$route.query.return;
              this.$router.push({ path: url + '?' + new Date().getTime() });
            } else if (res.errcode === 550006) {
              const msg = this.$t(
                'cloudpivot.form.runtime.tip.errTips13',
              ).toString();
              this.$message.error(msg);
              this.$h3.toast.show({
                text: msg,
                iconType: 'close',
              });
            } else {
              this.$h3.toast.show({
                text: res.errmsg as string,
                iconType: 'close',
              });
            }
          },
        },
      ],
    });
  }

  loadAsync() {
    if (!this.workflowInstanceId) {
      return;
    }

    // 获取流程实例信息
    workflowApi
      .getWorkflowBaseInfo({ workflowInstanceId: this.workflowInstanceId })
      .then((resp) => {
        if (resp.errcode !== 0) {
          throw resp.errmsg;
        }
        this.workflowInfo = resp.data || {};
      })
      .catch((err) => this.$h3.toast.show({ text: err.toString() }));
  }

  onDetail(params: any) {
    this.$router
      .push({
        name: 'FormApprovalDetails',
        params,
      })
      .catch((err: any) => {
        console.log(err);
      });
  }
}
</script>

<style lang="less">
@import '~cloudpivot/common/styles/mixins.less';
@import '~cloudpivot/common/styles/mobile/themes/default.less';

.workflow-track-wrapper {
  color: @first-level-black;
  .px2rem(top, 88px);
  overflow: hidden !important;
  //单独路由进入的页面，弹窗样式去除
  &.single-route {
    .px2rem(top, 0);
  }
  .h3think-popup-modal__header {
    border-bottom: unset;
    position: relative;
    .h3think-tabs {
      border-bottom: unset;
      box-shadow: inset 0px -0.5px 0px 0px rgba(209, 211, 228, 0.65);
      .px2remDouble(padding, 0, 36px);
      .h3think-tab__wrap {
        display: block;
        .h3think-tab__title {
          text-align: center;
          width: 50%;
          display: inline-block;
          max-width: unset;
          .px2remQuadruple(padding, 17px, 0, 17px, 0);
          .px2rem(height, 112px);
          &.active {
            .h3think-tab__title-text {
              font-weight: bold;
            }
          }
          .h3think-tab__title-text {
            .px2rem(font-size, 30px);
            .px2rem(line-height, 44px);
            &::after {
              .px2rem(border-radius, 2px);
              .px2rem(bottom, -36px);
            }
          }
        }
      }
    }
    .h-icon-all-close {
      position: absolute;
      .px2rem(line-height, 40px);
      .px2rem(right, 32px);
      .px2rem(top, 40px);
      .px2rem(font-size, 40px);
    }
  }
  .h3think-popup-modal__body {
    .calcAttr(height, 56);
    .workflow-track {
      height: 100%;
      .tab-content {
        overflow: auto;
        height: 100%;
        &::-webkit-scrollbar {
          display: none;
        }
        &.show-devops {
          .calcAttr(height, 62);
        }
        .scroll {
          height: 100%;
        }
      }
      .devOps {
        box-shadow: inset 0px 0.5px 0px 0px rgba(209, 211, 228, 0.65);
        .px2rem(height, 124px);
        .px2remQuadruple(padding, 12px, 16px, 10px, 16px);
        button {
          background: #2970ff;
          color: #fff;
          border: unset;
          .px2rem(border-radius, 12px);
          .px2rem(height, 80px);
        }
      }
    }
  }
}

.h3-toast-mask {
  z-index: 9999;
}
</style>
